<template>
  <div class="flex justify-end p-2">
    <router-link to="/article/createarticle">
      <Button label="发布文章" icon="pi pi-plus" class="p-button-sm" />
    </router-link>
  </div>
  <DataTable
    :value="articles"
    :resizableColumns="true"
    columnResizeMode="fit"
    showGridlines
    responsiveLayout="scroll"
    class="p-datatable-sm"
  >
    <Column field="dictCategory.value" header="分类"></Column>
    <Column field="title" header="标题"></Column>
    <Column field="source" header="来源"></Column>
    <Column field="created" header="发布时间"></Column>
    <Column header="查看">
      <template #body="props">
        <a class="text-indigo-500" :href="'/article/' + props.data.aid" target="_blank">查看</a>
        <span class="text-red-500 ml-2 cursor-pointer" @click="_deleteArticle(props.data.aid)">删除</span>
      </template>
    </Column>
    <template #footer>
      <div class="flex justify-center">空空如也~</div>
    </template>
  </DataTable>
</template>

<script lang="ts">
export default defineComponent({
  name: 'AccountArticle'
})
</script>

<script lang="ts" setup>
import { defineComponent, ref } from 'vue'
import { getArticleList, deleteArticle } from '@/api/user/article'
import { useToast } from 'primevue/usetoast'
import { useConfirm } from 'primevue/useconfirm'

import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import Button from 'primevue/button'

let toast = useToast()
let confirm = useConfirm()

const articles = ref<any[]>()

function _getArticleList() {
  getArticleList()
    .then(res => {
      articles.value = res.data
    })
    .catch(err => {
      toast.add({
        severity: 'error',
        summary: '获取文章列表失败',
        detail: err.data.msg,
        life: 3000
      })
    })
}

function _deleteArticle(id: string) {
  confirm.require({
    message: '确定要删除该文章吗？',
    header: '删除文章',
    icon: 'pi pi-exclamation-triangle',
    accept: () => {
      deleteArticle(id)
        .then(res => {
          toast.add({
            severity: 'success',
            summary: '删除成功',
            detail: res.data.msg,
            life: 3000
          })
          _getArticleList()
        })
        .catch(err => {
          toast.add({
            severity: 'error',
            summary: '删除失败',
            detail: err.data.msg,
            life: 3000
          })
        })
    },
    reject: () => {}
  })
}

_getArticleList()

</script>